﻿using ChoMy.Models;
using ChoMy.Models.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ChoMy.Helpers
{
    public class CategoryHelper
    {
        private ChoMyContext db = new ChoMyContext();

        public List<Category> Child(int id)
        {
            var result = new List<Category>();

            List<Category> categories = db.Categories.Where(x => x.ParentId == id).ToList();

            result.AddRange(categories);

            foreach (var cate in categories)
            {
                result.AddRange(Child(cate.Id));
            }

            return result;
        }

        public List<Category> Parent(int id)
        {
            var result = new List<Category>();

            Category category = db.Categories.Find(id);

            while (category.ParentId != null)
            {
                result.Add(category);
                category = db.Categories.Find(category.ParentId);
            }

            result.Add(category);

            return result;
        }

        public List<Category> Leaf()
        {
            return db.Categories
                .Where(x => !db.Categories.Select(y => y.ParentId).Contains(x.Id))
                .ToList();
        }

        public List<Category> Tree(int id)
        {
            var result = new List<Category>();

            result.AddRange(Child(id));
            result.AddRange(Parent(id));

            return result;
        }
    }
}